package com.cc.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.cc.config.AliYunOssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Import(AliYunOssConfig.class)
public class AliYunOssUtils {
    @Autowired
    private AliYunOssConfig aliYunOssConfig;
    /**
     * 使用阿里云oss存储文件 返回该文件的访问地址
     * @return 文件的访问地址
     */
    public  String uploadFile(String fileName, InputStream inputStream){
        //创建oss对象
        OSS ossClient = new OSSClientBuilder().build(aliYunOssConfig.getEndpoint(),aliYunOssConfig.getAccessKeyId(), aliYunOssConfig.getAccessKeySecret());
        // 上传文件
        //设置文件最终的路径和名称
        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        //参数1: 桶名字  参数2: 图片上传后名字   参数3: 图片流
        PutObjectResult putObjectResult = ossClient.putObject(aliYunOssConfig.getBucketName(), objectName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        //https://桶的名字.区域的名字/文件名
        return "https://" + aliYunOssConfig.getBucketName() + "." + aliYunOssConfig.getEndpoint().split("//")[1] + "/" + objectName;
    }
}
